
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/constants.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/event/event.dart';
import 'package:osc/event/event_constant.dart';
import 'package:osc/models/entity/osc_medal_entity.dart';
import 'package:osc/models/entity/osc_skill_radar_map_entity.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/entity/widget_item/share_item.dart';
import 'package:osc/models/entity/widget_item/user_center_item.dart';
import 'package:osc/models/local_data/share_item_data.dart';
import 'package:osc/models/local_data/user_center_item_data.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/colors.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/blog/blog_list.dart';
import 'package:osc/ui/pages/common_page.dart';
import 'package:osc/ui/pages/medal/medal_page.dart';
import 'package:osc/ui/pages/message/message_page.dart';
import 'package:osc/ui/pages/my/event_list.dart';
import 'package:osc/ui/pages/my/favorite_list.dart';
import 'package:osc/ui/pages/my/question_list.dart';
import 'package:osc/ui/pages/my/read_record_list.dart';
import 'package:osc/ui/pages/my/tag_list.dart';
import 'package:osc/ui/pages/other/setting.dart';
import 'package:osc/ui/pages/tweet/tweet_list_page.dart';
import 'package:osc/ui/pages/user/blacklist.dart';
import 'package:osc/ui/pages/user/friend_list_page.dart';
import 'package:osc/ui/pages/user/user_ability_cobweb_view.dart';
import 'package:osc/ui/widgets/button/pd_button.dart';
import 'package:osc/ui/widgets/medal/medal_list_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/share_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qr_flutter/qr_flutter.dart';

class Mine extends StatefulWidget{

  const Mine({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new MineState();
  }
}

class MineState extends State<Mine> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin<Mine>{
  MineState();

  OscUser user;
  OscSkillRadarMapEntity skillRadarMapEntity;
  List<OscMedal> medals;
  int medalCount = 0;

  int userId;
  int gender = 0;
  String userName = "";
  String portrait;
  bool isLogin = false;

  int tweetCount = 0;
  int collectCount = 0;
  int focusCount = 0;
  int fansCount = 0;



  List<ShareItem> shareItems;

  List<UserCenterItem> myItems;
  HttpRepository httpRepository;


  double expandedHeight = 0;
  double appBarHeight = 0;

  int maxScore = 100;
  List<double> scores = [0, 0, 0, 0, 0, 0];

  RefreshController refreshController;
  ScrollController scrollController;
  TabController tabController;


  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    appBarHeight = Dimens.view_app_bar_height_mine;
    onBusEvent();
    isLogin = OscUserManager.instance.isLogin();
    userId = OscUserManager().getUserId();
    userName = OscUserManager().getUserName();
    portrait = OscUserManager().getPortrait();
    myItems = UserCenterItemData().getItems();
    shareItems = ShareItemData().getItems();
    refreshController = RefreshController(initialRefresh: true);
    scrollController = ScrollController();
    tabController = TabController(length: 4, vsync: this);
    httpRepository = new HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
    offBusEvent();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    expandedHeight = ScreenUtil.getInstance().screenWidth;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SmartRefresher(
          controller: refreshController,
        onRefresh: refresh,
        enablePullUp: false,
        child: buildCustomScrollView(),
      ),
    );
  }

  buildCustomScrollView(){
    return CustomScrollView(
      controller: scrollController,
      slivers: <Widget>[
          SliverAppBar(
            backgroundColor: Theme.of(context).primaryColor,
            expandedHeight: expandedHeight*4/5,
            title: buildProfile(),
            actions: <Widget>[
              buildAction("btn_my_setting", (){
                jump2Page(SettingPage(), checkLogin: true);
              }),
              buildAction("btn_qrcode", (){
                showQrCodeDialog();
              }),
            ],
            primary: true,//是否预留高度,ture时在状态栏下，false 最上面
//            snap: false,//折叠效果，与floating结合使用，如果为true则floating必须为true,就是往下滑一点整个大背景就显示全部，往上滑动整个导航内容就隐藏
            floating: false,//是否随滑动隐藏标题,则滑动到最上面再滑动是否隐藏标题，ture隐藏
            pinned: true,//是否固定导航在顶部，true 固定，false不固定，再上滑导航隐藏
            flexibleSpace: FlexibleSpaceBar(
              centerTitle: true,
              background: SizedBox(
                width: expandedHeight*4/5,
                height: expandedHeight*4/5,
                child: CustomPaint(
                  painter: UserAbilityCobwebView(scores: scores, maxRadius: expandedHeight/8, skills: Constant.SKILLS),
                ),
              ),
            ),
            bottom: PreferredSize(
                child: buildBottom(),
                preferredSize: Size.fromHeight(Dimens.view_item_height_normal),
            ),
          ),
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index){
                  return buildItem(myItems.elementAt(index));
                },
                childCount: myItems.length,
              ),
              itemExtent: Dimens.view_item_height_big,
          ),
        ]
    );
  }

  buildBottom(){
    return Container(
      child: Column(
        children: <Widget>[
          MedalListWidget(userId: userId, gender: gender, medals: medals,),
          buildTabBar(),
        ],
      ),
    );
  }

  buildTabBar(){
    return Container(
      padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal),
      color: Color(0x36000000),
      child: TabBar(
        onTap: (int index){
          switch(index){
            case 0:
              jump2Page(TweetListPage(authorId: userId,), checkLogin: true);
              break;
            case 1:
              jump2Page(CommonPage(title: "收藏", body: FavoriteList()), checkLogin: true);
              break;
            case 2:
              jump2Page(FriendListPage(relation: 1, userId: userId,), checkLogin: true);
              break;
            case 3:
              jump2Page(FriendListPage(relation: 0, userId: userId,), checkLogin: true);
              break;
          }
        },
        indicatorColor: Colors.transparent,
        indicatorWeight: 1,
        tabs: [
          buildTab("猿圈", tweetCount),
          buildTab("收藏", collectCount),
          buildTab("关注", focusCount),
          buildTab("粉丝", fansCount),
        ],
        controller: tabController,
      ),
    );
  }

  buildTab(String data, int number){
    return Column(
      children: <Widget>[
        SmallWidgets.buildText("$number", Colors.white, Dimens.font_sp20),
        SmallWidgets.buildText(data, Colors.white, Dimens.font_sp12),
      ],
    );
  }


  buildProfile(){
    return Padding(
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal, vertical: Dimens.gap_view_normal),
      child: Row(
        children: <Widget>[
          buildPortrait(),
          buildUserNameOrLoginButton(),
        ],
      ),
    );
  }

  buildPortrait(){
    Widget child;
    if(user == null || StringUtil.isEmpty(portrait)){
      child = Image.asset(PdUtil.getImagePath("ic_author"), width: 50,);
    } else {
      child = OscPortraitWidget(
        id: userId,
        portraitImageUrl: portrait,
        showGender: true,
        gender: gender,
        size: Dimens.view_portrait_size,
      );
    }
    return Padding(
      padding: EdgeInsets.only(right: Dimens.gap_view_bigger),
      child: child,
    );
  }

  buildUserNameOrLoginButton(){
    Widget userNameWidget = Text(userName??"", style: TextStyle(color: Colors.white, fontSize: Dimens.font_sp16));

    Widget loginWidget = InkWell(
        onTap: (){
          jump2PageForResult(LoginPage());
        },
        child: Text(StringIds.login, style: TextStyle(color: Colors.white, fontSize: Dimens.font_sp16))
    );

    return Expanded(
        child: isLogin? userNameWidget : loginWidget,
    );
  }

  buildAction(String imageName, Function function){
    return SmallWidgets.buildActionIconButton(imageName: imageName, onTap: function, context: context);
  }


  buildItem(UserCenterItem item){
    String imageName = item.imageName;
    String title = item.title;
    String extract = item.extract;
    return GestureDetector(
      onTap: (){
        onItemClick(item);
      },
      child: Container(
        margin: EdgeInsets.only(bottom: Dimens.gap_divider_height_smallest),
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: 0),
        color: Colors.white,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal, horizontal: Dimens.gap_view_normal),
              child: Image.asset(PdUtil.getImagePath(imageName), height: Dimens.view_item_icon_height_normal, fit: BoxFit.fitHeight,),
            ),
            Expanded(
                flex: 1,
                child: Text(title, style: TextStyle(fontSize: Dimens.font_sp16, color: Colors.black),)
            ),
            Text(extract, style: TextStyle(fontSize: Dimens.font_sp12, color: Colours.gray_33),),
            buildArrowRight()
          ],
        ),
      ),
    );
  }

  buildButton(String text, Color textColor, Color bg, EdgeInsetsGeometry padding, Function onPressed){
    return Expanded(
      flex: 1,
        child: Padding(
            padding: padding,
          child: FlatButton(
              color: bg,
              onPressed: onPressed,
              child: Text(text, style: TextStyle(fontSize: Dimens.font_sp16, color: textColor),)
          ),
        )
    );
  }

  buildLine(){
    return SmallWidgets.buildLine();
  }
  buildLineBigger(){
    return SmallWidgets.buildLineBigger();
  }

  buildArrowRight(){
    return Padding(
        padding: EdgeInsets.only(left: Dimens.gap_view_normal),
      child: Image.asset(PdUtil.getImagePath("ic_arrow_right"), height: Dimens.view_item_icon_height_smaller, fit: BoxFit.fitHeight,),
    );
  }

  showShareDialog(){
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.white,
        builder: (BuildContext context){
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              buildShareGrid(),
              Divider(height: Dimens.gap_view_smaller,),
              PdButton(
                onTap: (){
                  Navigator.pop(context);
                },
                data: "取消",
                width: ScreenUtil.getScreenW(context),
                height: Dimens.view_button_height_normal,
                textStyle: MyTextStyle.SHEET_BUTTON,
              ),
            ],
          );
        }
    );
  }

  buildShareGrid(){
    return GridView.builder(
      shrinkWrap: true,
      primary: false,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
      ),
      itemBuilder: (BuildContext context, int index){
        return buildShareItem(index: index);
      },
      itemCount: shareItems.length,
    );
  }



  buildShareItem({@required int index}){
    ShareItem item = shareItems.elementAt(index);
    return GestureDetector(
      onTap: (){
        switch(item.type){
          case ShareItem.TYPE_WEIBO:
          case ShareItem.TYPE_FRIEND:
          case ShareItem.TYPE_WECHAT:
          case ShareItem.TYPE_QQ:
            ShareUtil.shareUrl(item.type);
            break;
          case ShareItem.TYPE_TWEET:
            showTips("暂不支持分享到猿圈");
            break;
          case ShareItem.TYPE_BROWSER:
            NavigatorUtil.launchInBrowser(ShareUtil.shareTargetUrl);
            break;
          case ShareItem.TYPE_COPY_URL:
            Clipboard.setData(ClipboardData(text: ShareUtil.shareTargetUrl));
            showTips("已复制到粘贴板");
            break;
          case ShareItem.TYPE_MORE:
            ShareUtil.shareUrl(item.type);
            break;
        }
        Navigator.pop(context);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(PdUtil.getImagePath(item.imageName), width: Dimens.view_item_icon_height_bigger, fit: BoxFit.contain,),
          Divider(color: Colors.transparent, height: Dimens.gap_view_normal,),
          Text(item.name, style: MyTextStyle.LIST_BODY,),
        ],
      ),
    );
  }

  showQrCodeDialog(){
    showDialog(
        context: context,
      builder: (BuildContext context){
          return AlertDialog(
            contentPadding: EdgeInsets.all(Dimens.gap_activity_horizontal),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: Dimens.view_qr_code_image_size,
                  height: Dimens.view_qr_code_image_size,
                  child: QrImage(
                    data: "${Constant.USER_QR_CODE_PREFIX_HTTPS}$userId",
                  ),
                ),
                Text("扫一扫上面的二维码，加我为好友", style: MyTextStyle.LIST_BODY,),
              ],
            ),
          );
      }
    );
  }

  logout(){
    OscUserManager.instance.logout();
    user = null;
    isLogin = false;
    setState(() {
    });
  }


  onItemClick(UserCenterItem item){
    switch(item.id){
      case UserCenterItem.ID_MY_MESSAGE:
        jump2Page(MessagePage(), checkLogin: true);
        break;
      case UserCenterItem.ID_MY_MEDAL:
        jump2Page(MedalPage(userId: userId, gender: gender,), checkLogin: true);
        break;
      case UserCenterItem.ID_READ_HISTORY:
        jump2Page(CommonPage(title: item.title, body: ReadRecordList()), checkLogin: true);
        break;
      case UserCenterItem.ID_MY_BLOG:
        jump2Page(CommonPage(title: item.title, body: BlogList(authorUid: userId,)), checkLogin: true);
        break;
      case UserCenterItem.ID_MY_BLACKLIST:
        jump2Page(CommonPage(title: item.title, body: Blacklist()), checkLogin: true);
        break;
      case UserCenterItem.ID_MY_QUESTION:
        jump2Page(CommonPage(title: item.title, body: QuestionList(authorId: userId,)), checkLogin: true);
        break;
      case UserCenterItem.ID_MY_DELIVER:
        jump2Page(CommonPage(title: item.title, body: EventList(authorId: userId,)), checkLogin: true);
        break;
      case UserCenterItem.ID_MY_ACTIVE:
        jump2Page(CommonPage(title: item.title, body: EventList(authorId: userId)), checkLogin: true);
        break;
      case UserCenterItem.ID_FOCUS_TAG:
        jump2Page(CommonPage(title: item.title, body: TagList()), checkLogin: true);
        break;
      case UserCenterItem.ID_INVITE_FRIEND:
        showShareDialog();
        break;
    }
  }

  jump2Page(Widget page, {bool checkLogin = false}){
    if(checkLogin && !isLogin){
      jump2PageForResult(LoginPage());
    } else {
      NavigatorUtil.pushPage(context, page);
    }
  }
  jump2PageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            if(result.success){
              user = result.object as OscUser;
              updateUserInfo(user);
              setState(() {
                isLogin = true;
              });
            }
            break;
          case PopResult.ID_LOGOUT:
            if(result.success){
              setState(() {
                isLogin = false;
                userName = null;
                portrait = null;
                user = null;
                tweetCount = 0;
                collectCount = 0;
                focusCount = 0;
                fansCount = 0;
                medalCount = 0;
                medals.clear();
                scores.clear();
              });
            }
            break;
        }
      }
    });
  }
  jump2Web(String url, String title){
    NavigatorUtil.pushWeb(context, url: url, title: title);
  }

  Future<Null> refresh() async{
    getUserInfo();
  }

  Future<Null> getUserInfo() async{
    if(isLogin) {
      await httpRepository.getUserInfoV2(userId: userId).then((resp) {
        if(resp.success){
          user = resp.result;
          updateUserInfo(user);
        } else {

        }
      });
    }
    if (mounted) {
      setState(() {
        refreshController.refreshCompleted();
      });
    }
  }

  updateUserInfo(OscUser user){
    if(user != null) {
      userId = user.id;
      gender = user.gender;
      userName = user.name;
      portrait = user.portrait;
      OscUserStatistics statistics = user.statistics;
      if(statistics != null) {
        tweetCount = statistics.tweet ?? 0;
        collectCount = statistics.collect ?? 0;
        focusCount = statistics.follow ?? 0;
        fansCount = statistics.fans ?? 0;
      }
      if(user.more != null) {
        scores = user.more.radar;
        medals = user.more.medals;
        medalCount = medals.length ?? 0;
      }

      OscUserManager.instance.setUser(user);
    }
  }

  onBusEvent(){
    eventBus.on(EventConstant.LOGIN, (tag){
      isLogin = OscUserManager.instance.isLogin();
      refresh();
    });

    eventBus.on(EventConstant.LOGOUT, (tag){
      setState(() {
        isLogin = false;
        userName = null;
        portrait = null;
        user = null;
      });
    });
  }
  offBusEvent(){
    eventBus.off(EventConstant.LOGIN);
    eventBus.off(EventConstant.LOGOUT);
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}